<template>
  <div id="detail">
    <!-- 详情页导航栏 -->
    <detail-nav-bar
      class="detailNav"
      @itemTab="itemTab"
      ref="detailnav"
    ></detail-nav-bar>

    <!-- 滚动区域 -->
    <scroll
      class="content"
      ref="scroll"
      :probe-type="3"
      :pull-up-load="true"
      @scrollPosition="contentScroll"
    >
      <!-- 顶部轮播图 -->
      <detail-swiper
        :top-img="topImg"
        @topImgLoad="detailImgLoad"
      ></detail-swiper>
      <!-- 商品基本描述 -->
      <detail-base-infos :detail-base-info="detailBaseInfo"></detail-base-infos>
      <!-- 商家详情 -->
      <detail-shop-info :shop-info="shopDetailInfo"></detail-shop-info>
      <!-- 商品更多详细信息 -->
      <detail-more-info
        :detail-more-info="detailMoreInfo"
        @moreImgLoad="detailImgLoad"
      ></detail-more-info>
      <!-- 商品参数信息-->
      <detail-goods-params
        ref="goodsparams"
        :goods-params="goodsParams"
      ></detail-goods-params>
      <!--  商品评论信息-->
      <detail-goods-coment
        ref="goodscoment"
        :goods-coment="goodsComent"
      ></detail-goods-coment>
      <!-- 更多推荐商品 -->
      <h3 ref="goodsrec">更多推荐</h3>
      <goods-list :goods="recommends"></goods-list>
    </scroll>
    <!-- 底部购物车栏 -->
    <detail-botbar @addCart="addToCart"></detail-botbar>
    <!-- 点击 加入购物车后的选项卡 -->
    <detaile-bot-cart
      :cart-goods="cartGoods"
      v-show="isOpenCart"
      @close="closeCart"
      @okAddCart="okAddCart"
    ></detaile-bot-cart>
    <!-- 返回顶部按钮 -->
    <back-top @click.native="backTop" v-show="isShowBack"></back-top>
  </div>
</template>

<script>
import {
  getDetail, // 网络请求相关模块
  getRecommend,
  DetailBaseInfo, //商品基本描述的类
  ShopDetailInfo, // 商家详情数据的类
} from "network/detail/detail";
// 公共组件
import Scroll from "components/common/scroll/Scroll";
import Toast from "../../components/common/toast/Toast.vue";
// 子组件相关模块
import DetailNavBar from "./childComps/DetailNavBar";
import DetailSwiper from "./childComps/DetailSwiper.vue";
import DetailBaseInfos from "./childComps/DetailBaseInfos";
import DetailShopInfo from "./childComps/DetailShopInfo";
import DetailMoreInfo from "./childComps/DetailMoreInfo.vue";
import DetailGoodsParams from "./childComps/DetailGoodsParams.vue";
import DetailGoodsComent from "./childComps/DetailGoodsComent.vue";
import GoodsList from "components/content/goods/GoodsList.vue";
import DetailBotbar from "./childComps/DetailBotbar.vue";
import DetaileBotCart from "./childComps/DetaileBotCart.vue";
// 导入mixin混入对象
import { backTopMixin } from "common/mixin";
export default {
  name: "Detail",
  // 使用混入mixin
  mixins: [backTopMixin],
  components: {
    Scroll,
    DetailNavBar,
    DetailSwiper,
    DetailBaseInfos,
    DetailShopInfo,
    DetailMoreInfo,
    DetailGoodsParams,
    DetailGoodsComent,
    GoodsList,
    DetailBotbar,
    Toast,
    DetaileBotCart,
  },

  data() {
    return {
      iid: "",
      topImg: [], //顶部轮播图数据,
      detailBaseInfo: {}, //商品基本描述
      shopDetailInfo: {}, // 商家详情数据
      detailMoreInfo: {}, //商品更多详细信息
      goodsParams: {}, //商品参数信息
      goodsComent: {}, //商品评论信息
      recommends: [], //更多推荐数据
      cartGoods: {}, //购物车选项卡
      isOpenCart: false, //是否打开购物车选项卡
      themTopYs: [], //保存各组件距离顶部的Y值
      currentIndex: "", //防止滚动时获取i值太频繁
    };
  },

  //*生命周期函数 发送网络请求
  created() {
    //. 1 保存home传过来的iid
    this.iid = this.$route.params.iid;
    //. 2 根据iid请求对应的数据
    getDetail(this.iid).then((res) => {
      // console.log(res);
      const data = res.data.result;
      // console.log(data);
      //. 2.1 获取顶部轮播图数据
      this.topImg = data.itemInfo.topImages;
      //. 2.2 获取商品基本描述数据（通过导入一个 类 来将复杂的数据整合到一块，后面再传给子组件进行封装展示）
      this.detailBaseInfo = new DetailBaseInfo(
        data.itemInfo,
        data.columns,
        data.shopInfo.services
      );
      //. 2.3 获取商品对应的商家数据 通过导入一个类将复杂的数据整合到一块，后面再传给子组件进行封装展示
      this.shopDetailInfo = new ShopDetailInfo(data.shopInfo);
      //. 2.4 获取商品更多详细信息
      this.detailMoreInfo = data.detailInfo;
      //. 2.5 获取商品参数信息
      this.goodsParams = data.itemParams;
      //. 2.6 获取商品评论信息
      if (data.rate.cRate !== 0) {
        this.goodsComent = data.rate.list[0];
      }
      //. 2.7获取添加到购物车的信息
      this.cartGoods = data.skuInfo;

      //  this.$nextTick()将回调延迟到下次 DOM 更新循环之后执行。在修改数据之后立即使用它，然后等待 DOM 更新。
      // this.$nextTick(() => {
      //  根据最新的数据，对应的dom已经被渲染出来
      //  但是图片依然没有加载完成
      // });
    });

    //. 3 获取详情页的推荐数据
    getRecommend().then((res) => {
      this.recommends = res.data.data.list;
    });
  },

  //* 事件监听
  methods: {
    // 监听图片的加载
    detailImgLoad() {
      // 图片加载完后获取各个组件的Y值
      this.themTopYs = [];
      this.themTopYs.push(0);
      this.themTopYs.push(this.$refs.goodsparams.$el.offsetTop);
      this.themTopYs.push(this.$refs.goodscoment.$el.offsetTop);
      this.themTopYs.push(this.$refs.goodsrec.offsetTop);
      this.themTopYs.push(Number.MAX_VALUE);
    },

    // 点击tab选项卡滚动到对应位置
    itemTab(index) {
      // 先获取各组件的y坐标，在图片加载完成后获取
      // 根据index取出数组中要滚动的Y值
      this.$refs.scroll.scrollTo(0, -this.themTopYs[index]);
    },

    // 监听内容的滚动
    contentScroll(position) {
      // * 1 滚动到相应的位置时tab选项卡跟着变色
      const positionY = -position.y;
      let length = this.themTopYs.length;
      for (let i = 0; i < length - 1; i++) {
        //. 1.1 分情况判断，i < length - 1 时 和i === length - 1时，这样才能得到每一个i值
        // this.currentIndex != i，这是为了防止滚动是获取i值太频繁
        // if (
        //   (this.currentIndex != i &&
        //     (i < length - 1 &&
        //       positionY >= this.themTopYs[i] &&
        //       positionY < this.themTopYs[i + 1])) ||
        //       this.currentIndex != i &&
        //   (i === length - 1 && positionY >= this.themTopYs[i])
        // ) {
        //   this.currentIndex = i;
        // console.log(this.currentIndex);
        //   this.$refs.detailnav.currentIndex=this.currentIndex;
        // }

        //. 1.2 给数组最后加上一个非常大的值 用作判断
        if (
          this.currentIndex != i &&
          positionY > this.themTopYs[i] &&
          positionY < this.themTopYs[i + 1]
        ) {
          this.currentIndex = i;
          this.$refs.detailnav.currentIndex = this.currentIndex;
        }

        //* 当滚动的Y值大于1000时显示返回顶部按钮
        this.isShowBack = -position.y > 1000;
      }
    },

    // 关闭购物车Cart选项卡事件
    closeCart() {
      this.isOpenCart = false;
    },

    //点击加入购物车按钮后先打开购物车选项卡
    addToCart() {
      this.isOpenCart = true;
    },
    okAddCart(colorIndex, sizeIndex, count) {
      // console.log(colorIndex);
      // console.log(sizeIndex);
      this.isOpenCart = false;
      // 1 获取购物车需要展示的数据
      const product = {};
      product.image = this.topImg[0];
      product.title = this.detailBaseInfo.title;
      product.price = this.detailBaseInfo.realPrice;
      product.color = this.cartGoods.props[0].list[colorIndex].name;
      product.size = this.cartGoods.props[1].list[sizeIndex].name;
      product.count = count;
      product.iid = this.iid;
      // 2 将商品添加到购物车里(使用vuex进行状态管理)
      this.$store.dispatch("addCart", product).then((res) => {
        //*store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise，并且 store.dispatch 仍旧返回 Promise：

        //* 3 显示提示框
        // 3.1 传统组件方法
        // console.log(res);
        // this.msg = res;
        // this.showMsg = true;
        // setTimeout(() => {
        //   this.showMsg = false;
        // }, 1500);
        //. 3.2 自定义插件方法
        // console.log(this.$toast);
        this.$toast.showMsg(res);
      });
    },
  },
};
</script>

<style scoped>
#detail {
  position: fixed;
  left: 0;
  right: 0;
  z-index: 9;
  background: #fff;
  height: 100vh;
}
.detailNav {
  position: relative;
  z-index: 99;
  background: #fff;
}
.content {
  height: calc(100% - 98px);
  overflow: hidden;
}
h3 {
  margin: 30px 0 0 12px;
}
</style>
